package modes

import (
	"fmt"
	"time"
)

/*课程表*/
type Culum struct {
	Id      int64 `json:"culum_id" xorm:"id"`             //课程id
	Pid     int64 `json:"culum_pid" xorm:"pid"`           //项目id
	Sid     int64 `json:"culum_sid" xorm:"sid"`           //科目id
	SType   int64 `json:"culum_s_type" xorm:"s_type"`     //课程类型
	SFormat int64 `json:"culum_s_format" xorm:"s_format"` //资源格式
	At      int64 `json:"culum_at" xorm:"at"`             //创建时间
	Start   int64 `json:"culum_start" xorm:"start"`       //状态
}

func (this *Culum) TableName() string {
	return "culum"
}
func (this *Culum) Save() (int64, error) {
	this.At = time.Now().Unix()
	return Db(0).Insert(this)
}

func (this *Culum) Get() (bool, error) {
	return Db(0).Get(this)
}
func (this *Culum) delete(where string) (int64, error) {
	return Db(0).Where(where).Delete(this)
}
func (this *Culum) Del() (int64, error) {
	where := fmt.Sprintf("id =%d", this.Id)
	return this.delete(where)
}
func (this *Culum) Count(where string) (int64, error) {
	var val Culum
	return Db(0).Where(where).Count(&val)
}
func (this *Culum) update(where string, field string) (int64, error) {
	return Db(0).Where(where).Cols(field).Update(this)
}

func (this *Culum) IdSet(field string) (int64, error) {
	where := fmt.Sprintf("id = %d", this.Id)
	return this.update(where, field)
}

func (this *Culum) where(fage, count, page int, where, field string) ([]Culum, error) {
	list := make([]Culum, 0)
	var err error
	if field == "" {
		field = "id"
	}
	if 0 == fage { // 从小到大排序
		err = Db(0).Where(where).
			Asc(field).
			Limit(count, page*count).
			Find(&list)
	} else { // 从大到小排序
		err = Db(0).Where(where).
			Desc(field).
			Limit(count, page*count).
			Find(&list)
	}
	return list, err
}
func (this *Culum) List(val *Pager) error {
	val.TName = this.TableName()
	w := fmt.Sprintf("id = %d ", this.Id)
	val.Total, _ = this.Count(w)
	list, err := this.where(val.Rules, val.Count, val.Page-1, w, "")
	if err == nil {
		val.List = list
	}
	return err
}
